package ru.ifmo.swing.genetics.config.common;

import org.uncommons.watchmaker.swing.EvolutionControl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

/**
 * @author avhaliullin
 */
public class Chooser<T> extends ru.ifmo.swing.Panel {
    private final JComboBox control;
    private final Set<ChooserListener<T>> listeners = new HashSet<ChooserListener<T>>();
    private JComponent itemControl;
    private final Map<String, T> options;

    public Chooser(final Map<String, T> options) {
        this.options = options;
        this.control = new JComboBox(new Vector<String>(options.keySet()));
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        control.setPreferredSize(new Dimension(400, 25));
        control.setMaximumSize(new Dimension(400, 25));
        add(control);
        add(Box.createHorizontalStrut(10));

        this.control.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent ev) {
                if (ev.getStateChange() == ItemEvent.SELECTED) {
                    @SuppressWarnings("unchecked")
                    String itemName = (String) ev.getItem();
                    T item = options.get(itemName);
                    handleItem(item);
                    for (ChooserListener<T> listener : listeners) {
                        listener.chosen(item);
                    }
                }
            }
        });
        handleItem(getItem());
    }

    private void handleItem(T item) {
        if (itemControl != null) {
            itemControl.setVisible(false);
            remove(itemControl);
        }
        if (item instanceof EvolutionControl) {
            itemControl = ((EvolutionControl) item).getControl();
            Chooser.this.add(itemControl);
            itemControl.setVisible(true);
        }
    }

    public String getItemText() {
        return (String) control.getSelectedItem();
    }

    public T getItem() {
        @SuppressWarnings("unchecked")
        String itemName = (String) control.getSelectedItem();
        return options.get(itemName);
    }

    public void addListener(ChooserListener<T> listener) {
        listeners.add(listener);
        listener.chosen(getItem());
    }

    public void removeListener(ChooserListener<T> listener) {
        listeners.remove(listener);
    }

    public void reset() {
        control.setSelectedIndex(0);
    }
}
